import { getToken } from '@/services/api/auth';
import { TenantResultItem } from '@/services/api/model/tenantModel';
import { getList, getListName } from '@/services/api/tenants';
import {
  DeleteOutlined,
  DownOutlined,
  FormOutlined,
  PlusCircleFilled,
  SettingOutlined,
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Avatar, Button, Col, Dropdown, List, MenuProps, Row, Spin, Tooltip } from 'antd';
import moment from 'moment';
import { stringify } from 'querystring';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import style from './style.less';
const Area: React.FC = () => {
  const [tableData, setTabelData] = useState<TenantResultItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    flushSync(() => {
      setInitialState((s) => ({ ...s, currentUser: undefined }));
    });
    // await outLogin();
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      localStorage.removeItem('token');
      localStorage.removeItem('user_pas');
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };
  // 获取用户信息
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  // 取出缓存的账号密码
  const user_pas = localStorage.getItem('user_pas');
  const userPasInfo = user_pas ? JSON.parse(user_pas) : null;
  useEffect(() => {
    getList().then(async (res) => {
      const resultsList = res.results;
      const names = await getListName({
        ...userPasInfo,
      });
      const { data } = names;
      const tenantList = data?.tenantList;
      tenantList?.forEach((item) => {
        resultsList?.forEach((li) => {
          if (li.token === item.token) {
            li.tenantId = item.tenantId;
          }
        });
      });
      setTabelData(resultsList || []);
    });
  }, []);
  const handleItem = async (item: TenantResultItem) => {
    setLoading(true);
    try {
      const { tenantId } = item;
      const t = await getToken({
        ...userPasInfo,
        tenantId,
        grant_type: 'password',
      });
      localStorage.setItem('token', t.access_token);
      localStorage.setItem('tenant', JSON.stringify(item));
      await fetchUserInfo();
      // history.push('/');
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/');
      setLoading(false);
    } catch (error) {
      setLoading(false);
    }
  };
  const cardList = tableData && (
    <List<TenantResultItem>
      style={{
        padding: 10,
      }}
      grid={{
        gutter: 16,
        xs: 1,
        sm: 2,
        md: 3,
        lg: 3,
        xl: 4,
        xxl: 4,
      }}
      dataSource={tableData}
      renderItem={(item) => (
        <List.Item>
          <div className={style['tenan_item']} onClick={() => handleItem(item)}>
            <i className={style['topL']}></i>
            <i className={style['topR']}></i>
            <i className={style['bottomL']}></i>
            <i className={style['bottomR']}></i>
            <Avatar
              className={style['avatar_img']}
              src={<img src={IMG_URL + item.imageUrl} alt="avatar" />}
            />
            <div className={style['item_right']}>
              <div className={style['ten_name']}> {item.name} </div>
              <div className={style['ten_time']}>
                {moment(item.createdDate).format('YYYY-MM-DD HH:mm:ss')}
              </div>
              <Row>
                <Col
                  span={8}
                  style={{
                    textAlign: 'center',
                  }}
                >
                  <Tooltip title="search">
                    <Button type="primary" shape="circle" icon={<SettingOutlined />} />
                  </Tooltip>
                </Col>
                <Col
                  style={{
                    textAlign: 'center',
                  }}
                  span={8}
                >
                  <Tooltip title="search">
                    <Button type="primary" shape="circle" icon={<FormOutlined />} />
                  </Tooltip>
                </Col>
                <Col
                  style={{
                    textAlign: 'center',
                  }}
                  span={8}
                >
                  <Tooltip title="search">
                    <Button type="primary" shape="circle" icon={<DeleteOutlined />} />
                  </Tooltip>
                </Col>
              </Row>
            </div>
          </div>
        </List.Item>
      )}
    />
  );
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <a target="_blank" rel="noopener noreferrer" onClick={() => loginOut()}>
          退出
        </a>
      ),
    },
  ];
  return (
    <Spin spinning={loading} size="large">
      <div className={style['tenant-content']}>
        <div className={style['tenant-content-head']}>
          <div className={style['tenant-content-head-title']}>场景联动系统</div>
          <div className={style['tenant-content-head-btns']}>
            <PlusCircleFilled className={style['tenant-content-head-btns-add']} />
            <Dropdown.Button size="small" type="primary" icon={<DownOutlined />} menu={{ items }}>
              {userPasInfo?.username}
            </Dropdown.Button>
          </div>
        </div>
        <div className={style.cardList}>{cardList}</div>
      </div>
    </Spin>
  );
};

export default Area;
